extends Node

# Array to hold different enemy scenes you want to spawn
@export var enemy_scenes: Array[PackedScene] = [] # Assign your 5 enemy scenes here in the Inspector

@onready var spawn_timer = $SpawnTimer # Needs a Timer node named SpawnTimer

# Spawn control variables
var base_spawn_interval = 2.0
var min_spawn_interval = 0.2
var interval_decrease_rate = 0.05 # How much interval decreases per wave/time
var enemies_per_spawn = 1
var max_enemies_per_spawn = 10
var increase_count_interval = 15 # Increase count every 15 seconds (example)

var time_elapsed = 0.0
var time_since_last_count_increase = 0.0

func _ready():
	if enemy_scenes.is_empty():
		print("WARNING: EnemySpawner has no enemy scenes assigned!")
		return
	spawn_timer.wait_time = base_spawn_interval
	spawn_timer.start()

func _process(delta):
	time_elapsed += delta
	time_since_last_count_increase += delta

	# Gradually decrease spawn interval
	var current_interval = max(min_spawn_interval, base_spawn_interval - (time_elapsed * interval_decrease_rate * 0.1)) # Adjusted rate
	spawn_timer.wait_time = current_interval

	# Gradually increase enemies per spawn
	if time_since_last_count_increase >= increase_count_interval:
		enemies_per_spawn = min(max_enemies_per_spawn, enemies_per_spawn + 1)
		time_since_last_count_increase = 0.0
		print("Increasing enemies per spawn to: ", enemies_per_spawn)


func _on_spawn_timer_timeout():
	spawn_enemies()

func spawn_enemies():
	var player = get_tree().get_first_node_in_group("player")
	if not player or enemy_scenes.is_empty():
		return # Don't spawn if player doesn't exist or no scenes defined

	var viewport_rect = get_viewport().get_visible_rect()
	var spawn_radius = (viewport_rect.size.x + viewport_rect.size.y) / 2.0 # Radius slightly outside view
	var enemies_container = get_tree().get_root().get_node("Main/Enemies") # Get container node

	for i in range(enemies_per_spawn):
		# Choose an enemy type (randomly for now, could be based on time)
		var enemy_scene = enemy_scenes.pick_random()

		# Calculate spawn position outside the screen
		var angle = randf_range(0, TAU) # TAU is 2 * PI
		var spawn_offset = Vector2(cos(angle), sin(angle)) * spawn_radius
		var spawn_position = player.global_position + spawn_offset

		# Instantiate and add the enemy
		var enemy_instance = enemy_scene.instantiate()
		enemies_container.add_child(enemy_instance)
		enemy_instance.global_position = spawn_position
		# print("Spawned enemy at: ", spawn_position)

# Add a Timer node named "SpawnTimer" as a child of this spawner scene in the editor.
# Connect its "timeout" signal to the _on_spawn_timer_timeout function.
# In the Inspector, populate the "Enemy Scenes" array with your 5 enemy scene files (e.g., drag & drop .tscn files).
